const { sequelize } = require('../utils/database');

async function checkTables() {
  try {
    console.log('检查数据库中的表...');
    
    const [results] = await sequelize.query("SHOW TABLES;");
    
    console.log('现有的表:');
    results.forEach((table, index) => {
      const tableName = Object.values(table)[0];
      console.log(`${index + 1}. ${tableName}`);
    });
    
    console.log('\n检查feeds表是否存在...');
    const [feedsCheck] = await sequelize.query("SHOW TABLES LIKE 'feeds';");
    
    if (feedsCheck.length === 0) {
      console.log('❌ feeds表不存在');
      console.log('尝试创建feeds表...');
      
      await sequelize.query(`
        CREATE TABLE IF NOT EXISTS feeds (
          id INT AUTO_INCREMENT PRIMARY KEY,
          user_id INT NOT NULL,
          activity_id INT NULL,
          content TEXT,
          media_urls JSON NULL,
          feed_type ENUM('post', 'photo', 'check_in', 'activity_share') DEFAULT 'post',
          likes_count INT DEFAULT 0,
          comments_count INT DEFAULT 0,
          is_public BOOLEAN DEFAULT TRUE,
          createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          INDEX idx_user_id (user_id),
          INDEX idx_activity_id (activity_id),
          INDEX idx_created_at (createdAt),
          FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
      `);
      console.log('✓ feeds表创建成功');
    } else {
      console.log('✓ feeds表存在');
    }
    
  } catch (error) {
    console.error('检查表失败:', error);
    throw error;
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  checkTables()
    .then(() => {
      console.log('表检查脚本执行完成');
      process.exit(0);
    })
    .catch(error => {
      console.error('表检查脚本执行失败:', error);
      process.exit(1);
    });
}

module.exports = { checkTables }; 